package com.dlc.shop.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dlc.shop.bean.dto.BrandShopDTO;
import com.dlc.shop.bean.dto.BrandSigningDTO;
import com.dlc.shop.bean.enums.SigningStatus;
import com.dlc.shop.bean.model.*;
import com.dlc.shop.common.annotation.RedisLock;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.jky.common.foreign.service.ForeignShopService;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.ProductService;
import com.dlc.shop.service.SigningAuditingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author lth
 * @Date 2021/8/19 10:19
 */
@RestController
@RequestMapping("/shop/signingAuditing")
@Tag(name = "签约信息接口")
@AllArgsConstructor
public class SigningAuditingController {

    private final SigningAuditingService signingAuditingService;
    private final ProductService productService;
    private final ForeignShopService foreignShopService;


    @GetMapping("/listApplySigningCategory")
    @Operation(summary = "获取可以签约的平台分类列表（已经签约的平台分类不会返回）" , description = "获取可以签约的平台分类列表（已经签约的平台分类不会返回）")
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:list')")
    public ServerResponseEntity<List<Category>> listApplySigningCategory() {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<Category> categoryList = signingAuditingService.listApplySigningCategory(shopId);
        return ServerResponseEntity.success(categoryList);
    }

    @GetMapping("/listApplySigningBrand")
    @Operation(summary = "获取可以签约的平台品牌列表（已经签约的平台品牌不会返回)" , description = "获取可以签约的平台品牌列表（已经签约的平台品牌不会返回)")
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:list')")
    public ServerResponseEntity<List<Brand>> listApplySigningBrand(Brand brand) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<Brand> brandList = signingAuditingService.listApplySigningBrand(shopId, brand);
        return ServerResponseEntity.success(brandList);
    }

    @PostMapping("/addSigningCategory")
    @Operation(summary = "增加签约分类" , description = "增加签约分类")
    @Parameters(value = @Parameter(name = "categoryShopList", description = "店铺签约分类id列表" ))
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:save')")
    public ServerResponseEntity<Void> addSigningCategory(@RequestBody List<CategoryShop> categoryShopList) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        signingAuditingService.addSigningCategory(categoryShopList, shopId);
        //组装数据发往 国外 增加签约分类
        for (CategoryShop categoryShop : categoryShopList) {
            categoryShop.setShopId(shopId);
        }
        foreignShopService.addSigningCategory(categoryShopList);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/deleteSigningCategory")
    @Operation(summary = "根据分类id删除签约分类" , description = "根据分类id删除签约分类")
    @Parameter(name = "categoryId", description = "分类Id" )
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:delete')")
    public ServerResponseEntity<Void> deleteSigningCategory(@RequestParam("categoryId") Long categoryId) {
        // 判断该分类下是否有商品
        Long shopId = SecurityUtils.getShopUser().getShopId();
        long categoryProdCount = productService.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1).eq(Product::getShopId,shopId).and(prod -> prod.eq(Product::getShopCategoryId,categoryId).or().eq(Product::getCategoryId, categoryId)));
        if (categoryProdCount > 0){
            // 该分类下还有商品，请先删除该分类下的商品
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.category.delete.check"));
        }

        signingAuditingService.deleteSigningCategory(shopId, categoryId);
        //国外版伤处 分类签约信息
        foreignShopService.deleteSigningCategory(shopId,categoryId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/addSigningBrand")
    @Operation(summary = "增加签约品牌" , description = "增加签约品牌")
    @RedisLock(lockName = "addSigningBrandLock",key ="#BrandSigningDTO")
    @Parameters(value = @Parameter(name = "brandSigningDTO", description = "店铺签约品牌id列表" ))
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:save')")
    public ServerResponseEntity<Void> addSigningBrand(@RequestBody BrandSigningDTO brandSigningDTO) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        signingAuditingService.addSigningBrand(brandSigningDTO.getPlatformBrandList(), shopId);

        //国外同步信息
        for (BrandShopDTO brandShopDTO : brandSigningDTO.getPlatformBrandList()) {
            brandShopDTO.setShopId(shopId);
        }
        foreignShopService.addSigningBrand(brandSigningDTO);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/deleteSigningBrand")
    @Operation(summary = "根据签约品牌Id删除签约品牌" , description = "根据签约品牌Id删除签约品牌")
    @Parameter(name = "brandShopId", description = "签约品牌Id" )
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:delete')")
    public ServerResponseEntity<Void> deleteSigningBrand(@RequestParam("brandShopId") Long brandShopId) {
        signingAuditingService.deleteSigningBrand(brandShopId);
        //往国外同步 店铺删除签约品牌id
        foreignShopService.deleteSigningBrand(brandShopId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/applyCategory")
    @Operation(summary = "申请签约分类" , description = "申请签约分类")
    @PreAuthorize("@pms.hasPermission('shop:shopCategory:apply')")
    public ServerResponseEntity<Void> applyCategory(@RequestBody List<CategoryShop> categoryShopList) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Long userId = SecurityUtils.getShopUser().getEmployeeId();
        signingAuditingService.applyCategory(shopId, userId, categoryShopList);
        return ServerResponseEntity.success();
    }

    @PostMapping("/applyBrand")
    @Operation(summary = "申请签约品牌" , description = "申请签约品牌")
    @PreAuthorize("@pms.hasPermission('shop:shopBrand:apply')")
    public ServerResponseEntity<Void> applyBrand(@RequestBody BrandSigningDTO brandSigningDTO) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Long userId = SecurityUtils.getShopUser().getEmployeeId();
        signingAuditingService.applyBrand(shopId, userId, brandSigningDTO.getPlatformBrandList());
        return ServerResponseEntity.success();
    }

    @PutMapping("/revoke")
    @Operation(summary = "撤销申请" , description = "撤销申请")
    @Parameter(name = "type", description = "类型：1：分类 2：品牌" )
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:delete')")
    public ServerResponseEntity<Void> revoke(@RequestBody Integer type) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        signingAuditingService.revoke(shopId, type);
        return ServerResponseEntity.success();
    }

    @GetMapping("/auditInfo")
    @Operation(summary = "查看签约审核信息" , description = "查看签约审核信息")
    @Parameter(name = "type", description = "类型：1：分类 2：品牌" )
    @PreAuthorize("@pms.hasPermission('shop:signingAuditing:info')")
    public ServerResponseEntity<SigningAuditing> auditInfo(@RequestParam(value = "type") Integer type) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        SigningAuditing signingAuditing = signingAuditingService.getOne(Wrappers.lambdaQuery(SigningAuditing.class)
                .eq(SigningAuditing::getShopId, shopId)
                .eq(SigningAuditing::getType, type)
                .ne(SigningAuditing::getStatus, SigningStatus.SUCCESS.value())
        );
        return ServerResponseEntity.success(signingAuditing);
    }
}
